package com.example.chessbattleplatform.web.chess_rooms.websocket;


import cn.hutool.json.JSONUtil;
import com.example.chessbattleplatform.Interceptor.WebSocketSetUserConfigurator;
import com.example.chessbattleplatform.Pojo.WebSocketSessionIdAndUserId;
import com.example.chessbattleplatform.web.chess_rooms.Pojo.dto.ListQueriesWebSocketDto;
import com.example.chessbattleplatform.web.chess_rooms.Pojo.websocket.ListQueriesSessionSendMessage;
import com.example.chessbattleplatform.web.chess_rooms.service.impl.RoomsServiceInterface;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@ServerEndpoint(value = "/ws/rooms/{current}/{limit}", configurator = WebSocketSetUserConfigurator.class)
// 房间列表渲染 数据发送
public class RoomsWebSocketServer {


    // 存储所有的session
    public static final ListQueriesSessionSendMessage webSocketSessionSendMessage = new ListQueriesSessionSendMessage();

    // 查询 service
    private static RoomsServiceInterface roomsService;

    //发送 列表 房间 数据
    public static void sendListQueriesMessage(Session session) {
        webSocketSessionSendMessage.sendListQueriesMessage(session, roomsService);
    }

    // 群发 列表 房间 数据
    public static void sendListQueriesMessage() {
        webSocketSessionSendMessage.sendListQueriesMessages(roomsService);
    }

    // 静态导入
    @Autowired
    public void setRoomsService(RoomsServiceInterface roomsService) {
        // 静态导入 房间服务
        RoomsWebSocketServer.roomsService = roomsService;
    }

    // 错误
    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
        log.info("Session：{} 链接,错误{}", session.getId(), throwable.getMessage());
    }

    /**
     * 列表查询房间
     *
     * @param current current – 当前页
     * @param limit   limit – 每页显示条数
     */
    @OnOpen
    public void onOpen(Session session, EndpointConfig config, @PathParam(value = "current") Long current, @PathParam("limit") Long limit) {

        // 获取token 并 校验
        Long user_id = Long.valueOf((String) config.getUserProperties().get("user_Id"));

        // 存储 session
        webSocketSessionSendMessage.addSessionMap(session, ListQueriesWebSocketDto.builder()
                        .current(current <= 0 ? 1 : current)
                        .limit(limit <= 0 ? 10 : limit)
                        .build(),
                WebSocketSessionIdAndUserId.builder()
                        .userId(user_id)
                        .session(session)
                        .build());

        sendListQueriesMessage(session);
    }

    // 链接关闭
    @OnClose
    public void onClose(Session session) {
        WebSocketSessionIdAndUserId remove = webSocketSessionSendMessage.deleteSessionMap(session);
//        log.info("Session：{} 链接关闭,删除", session.getId());
    }

    // 接收消息
    @OnMessage
    public void onMessage(Session session, String message) {
        log.info("收到消息:{}", message);
        if (!JSONUtil.isTypeJSON(message)) {
            log.info("不是 json 消息:{}", message);
            return;
        }
        ListQueriesWebSocketDto bean = JSONUtil.toBean(message, ListQueriesWebSocketDto.class);

        bean.setLimit(bean.getLimit() <= 0 ? 10 : bean.getLimit());
        bean.setCurrent(bean.getCurrent() <= 0 ? 1 : bean.getCurrent());

        // log.info("json 转化{}", bean);
        // 存储 session
        webSocketSessionSendMessage.updateSessionMap(session, bean);

        // 发送更新后的消息
        sendListQueriesMessage(session);
    }
}
